import { Component, OnInit, SimpleChanges } from '@angular/core';
import G6, { Graph } from '@antv/g6';
import { OrganizationInfo, PersonnelInfo } from 'src/app/models';
import { RoleService } from 'src/app/services/role.service';
import { OrganizationService } from 'src/app/services/organization.service';
import { DepartmentService } from 'src/app/services/department.service';
import { PersonnelService } from 'src/app/services/personnel.service';
import { ActivatedRoute, Router } from '@angular/router';  // 用于获取路由参数
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { JurisdictionModalComponent } from './jurisdiction-modal/jurisdiction-modal.component';
import { G6GraphEvent } from '@antv/g6/lib/interface/behavior';
import { PageTitleService } from 'src/app/services/page-title.service';
import { CodeItemPanleData, OrgCodeItemType } from './org-code-item/models';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer } from 'rxjs';
import { UploadService } from 'src/app/services/upload.service';
import { Tools } from 'src/app/common/tools/tools';
import { UploadHeaderComponent } from '../../employee/upload-header/upload-header.component';
import { UploadBackgroundComponent } from './upload-background/upload-background.component';

//./details-organization.component.html

@Component({
  selector: 'zepride-details-organization',
  templateUrl: './org-info.html',
  styleUrls: ['./details-organization.component.less']
})
export class DetailsOrganizationComponent implements OnInit {
  organizationInfo: OrganizationInfo = {} as OrganizationInfo;
  personnelInfo: PersonnelInfo = { orgTree: { id: '' }, acc: { id: '', password: '' } } as PersonnelInfo;
  treeList: { nodes: [], edges: [] };
  objectName: '';
  titleName = '';
  visible = false;
  globalFontSize = 12;
  personnellistOfData: []; //人员列表
  departmentlistOfData: []; //部门列表
  permitssList = []; //权限列表
  AccountPermitsList = []; //添加人员权限
  password: string; //密码
  TreeInfo: OrganizationInfo = {} as OrganizationInfo;
  UserInfo: PersonnelInfo = {} as PersonnelInfo;
  id: string;
  orgTreeId: string;
  presentId: string;
  superiorId: string;
  graph: Graph;
  isPersonnelVisible = false;
  isDepartmentVisible = false;
  isAccountVisible = false;
  isJurisdictionVisible = false;
  isConfirmLoading = false;
  departmentList = [];
  keyword = '';//关键字搜索
  keywordDepartments = ''; //部门关键字搜索
  isEqual = false;
  params = {
    id: '0',
    name: '',
    description: '',
    isGlobal: false,
    createTime: new Date().getTime()
  };
  codeValue = [];
  constructor(
    private organizationService: OrganizationService,
    private msg: NzMessageService,
    private route: Router,
    private activatedRoute: ActivatedRoute,
    private modal: NzModalService,
    private departmentService: DepartmentService,
    private personnelService: PersonnelService,
    private roleService: RoleService,
    private phSvr: PageTitleService,
    public uploadService: UploadService,
  ) {
    //获取编辑需要的参数
    activatedRoute.queryParams.subscribe(queryParams => {
      this.id = queryParams.Id;
      if (!this.id) {
        this.id = this.organizationService.orgid
      }
    });
  }

  async ngOnInit() {
    await this.getOrganizationInfoById();
    if (!this.organizationInfo.coverUrl) {
      this.organizationInfo.coverUrl = '../../../../../assets/images/img_05.png';
    }

    await this.getDepartments();

    await this.getOrgCodeRuleAndSeeds();
  }

  //查询详情
  async getOrganizationInfoById() {
    try {
      const data = await this.organizationService.getOrganizationInfoById(this.id);

      this.organizationInfo = data;
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  async getDepartments() {
    try {
      const data = await this.departmentService.queryDepartmentsList();
      this.departmentList = data.list;
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  getName(name) {
    switch (name) {
      case 'Organization': this.titleName = '机构信息'; break;
      case 'Department': this.titleName = '部门信息'; break;
      case 'User': this.titleName = '人员信息'; break;
    }
  }

  //角色权限
  async queryAccountPermitss() {
    try {
      const data = await this.roleService.queryAccountPermitss({ authObjectId: this.UserInfo.accountId, authObjectType: 'User' });
      //newArr 添加状态
      const newArr = data.permitConfig.map(v => {
        return { ...v, checked: false }
      })
      // //判断list 是否有值，有值代表有权限
      if (data.list.length) {
        data.permitConfig.filter(p => {
          data.list.find(i => {
            if (p.permitId == i.permitId) {
              return p.checked = true;
            }
          })
        })
        //插入保存数据this.roleParams.permits
        this.AccountPermitsList = data.list.map(v => {
          return {
            permitId: v.permitId,
            permitName: v.permitName,
            authObjectId: this.UserInfo.accountId,
            authObjectType: 'User'
          }
        })
      }
      // 遍历数据格式
      const result = [];
      data.permitConfig.forEach((item) => {
        var { groupName } = item;
        if (!result[groupName]) {
          result[groupName] = {
            groupName,
            checked: false,
            value: []
          }
        }
        result[groupName].value.push({ permitId: item.permitId, permitName: item.permitName, checked: item.checked });
      });

      this.permitssList = Object.values(result);
      this.permitssList.forEach(element => {
        this.isCheckAll(element);
      });
      this.modal.create({
        nzTitle: '人员权限',
        nzContent: JurisdictionModalComponent,
        nzFooter: null,
        nzComponentParams: {
          permitssList: this.permitssList,
          accountId: this.UserInfo.accountId
        }
      });
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  //跳转页面
  clickskip(url, type) {
    //列表
    if (type == 'list') {
      this.route.navigateByUrl(url);
      //编辑
    } else if (type == 'add') {
      this.route.navigate([url], { queryParams: { Id: 0, organizationId: this.id, parentId: this.presentId } });
    } else if (type == 'uplevel') {
      this.route.navigate([url], { queryParams: { Id: this.TreeInfo.id, parentId: this.presentId } });
    } else {
      this.route.navigate([url], { queryParams: { Id: this.id } });
    }
  }
  isCheckAll(permitssList) {
    permitssList.checked = permitssList.value.every(v => v.checked);
  }
  close() {
    this.visible = false;
  }

  handleCancel(type): void {
    if (type == 'personnel') {
      this.isPersonnelVisible = false;
    } else if (type == 'department') {
      this.isDepartmentVisible = false;
    } else if (type == 'account') {
      this.isAccountVisible = false;
    } else {
      this.isJurisdictionVisible = false;
    }
  }
  /**
* format the string
* @param {string} str The origin string
* @param {number} maxWidth max width
* @param {number} fontSize font size
* @return {string} the processed result
*/
  fittingString(str, maxWidth, fontSize) {
    const ellipsis = '...';
    const ellipsisLength = G6.Util.getTextSize(ellipsis, fontSize)[0];
    let currentWidth = 0;
    let res = str;
    const pattern = new RegExp('[\u4E00-\u9FA5]+'); // distinguish the Chinese charactors and letters
    str.split('').forEach((letter, i) => {
      if (currentWidth > maxWidth - ellipsisLength) return;
      if (pattern.test(letter)) {
        // Chinese charactors
        currentWidth += fontSize;
      } else {
        // get the width of single letter according to the fontSize
        currentWidth += G6.Util.getLetterWidth(letter, fontSize);
      }
      if (currentWidth > maxWidth - ellipsisLength) {
        res = `${str.substr(0, i)}${ellipsis}`;
      }
    });
    return res;
  };

  curTabIndex = 0;
  tabChange(tabIndex = 0) {
    this.curTabIndex = tabIndex;
  }

  private loading = false;
  handleChange(info: { file: NzUploadFile }, type): void {
    // this.type = type;
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        this.getBase64(info.file!.originFileObj!, (img: string) => {
          this.loading = false;
          if (type == 'logo') {
            //保存logo
            this.organizationInfo.logo = `${this.organizationService.uploadUrl}${info.file.response.fileUrl}`;
          } else if (type == 'license') {
            //保存营业执照赋值
            this.organizationInfo.businessLicenseUrl = `${this.organizationService.uploadUrl}${info.file.response.fileUrl}`;
          }
          else if (type == 'cover') {
            //封面
            this.organizationInfo.coverUrl = `${this.organizationService.uploadUrl}${info.file.response.fileUrl}`;
          }
          else {
            //保存组织结构代码证书
            this.organizationInfo.orgCodeUrl = `${this.organizationService.uploadUrl}${info.file.response.fileUrl}`;
          }

          this.saveOrgInfo();
        });
        break;
      case 'error':
        this.msg.error('Network error');
        this.loading = false;
        break;
    }
  }

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }

  async saveOrgInfo() {
    try {
      const data = await this.organizationService.updateOrganization(this.organizationInfo);
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    } finally {

    }
  }

  private orgCodeCount = 1;
  orgCodeList: CodeItemPanleData[] = [
    {
      id: Tools.GetGuid(),
      codeName: "编码" + this.orgCodeCount,
      orgCodeItems: [{
        id: Tools.GetGuid(),
        type: OrgCodeItemType.Settled,
        value: "001",
        canReset: true,
        codeBit: 3,
        resetRule: "month",
        incrementSeed: 1
      }],
      codeDisplays: []
    }
  ];

  private async getOrgCodeRuleAndSeeds() {
    let r = await this.organizationService.getOrgCodeSetting(this.organizationInfo.id);
    if (r) {
      this.orgCodeList.splice(0, 1);
      let list: any[] = r.data;
      list.forEach(item => {
        this.orgCodeList.push(item);
      });
      this.getOrgCodeDisplays(this.orgCodeList);
    }
  }

  addOrgCodeItem() {
    this.orgCodeCount++;
    this.orgCodeList.push({
      codeName: "编码" + this.orgCodeCount,
      id: Tools.GetGuid(),
      orgCodeItems: [
        {
          id: Tools.GetGuid(),
          type: OrgCodeItemType.Settled,
          value: "001",
          canReset: true,
          codeBit: 3,
          resetRule: "month",
          incrementSeed: 1
        }
      ],
      codeDisplays: []
    });
  }

  delOrgCodeItem(args: CodeItemPanleData) {
    let index = this.orgCodeList.findIndex(x => x.id == args.id);
    if (index > -1) {
      this.orgCodeList.splice(index, 1);
    }
  }

  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/bmp';
      if (!isJpgOrPng) {
        this.msg.error('You can only upload JPG file!');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('Image must smaller than 2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };

  async saveOrgCodes() {
    try {
      let list = Tools.cloneArrary(this.orgCodeList, ['com', 'codeDisplays']);
      this.getOrgCodeDisplays(this.orgCodeList);

      let codeNameList = [];
      for (let item of this.orgCodeList) {
        codeNameList = codeNameList.concat(item.codeDisplays);
      }

      for (let item of codeNameList) {
        let l = codeNameList.filter(x => x.codeName == item.codeName);
        if (l.length >= 2) {
          throw new Error(`重复的编码名称【${item.codeName}】`);
        }
      }

      await this.organizationService.saveOrgCodeRules(list);
      this.msg.success('编码保存成功！');
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  private getOrgCodeDisplays(list: CodeItemPanleData[]) {
    for (let item of list) {
      item.codeDisplays = [];
      let hasGroup = item.orgCodeItems.find(x => x.type == OrgCodeItemType.Group);
      if (hasGroup) {
        hasGroup.codeGroupItems.forEach(n => {
          item.codeDisplays.push({
            codeName: n.codeName,
            value: n.list.concat(item.orgCodeItems.filter(x => x.type != OrgCodeItemType.Group)).map(x => x.value).join('')
          })
        })
      }
      else {
        item.codeDisplays.push({
          codeName: item.codeName,
          value: item.orgCodeItems.map(x => x.value).join('')
        })
      }
    }
  }
  openConfigModal() {
    const nzTitle = '上传logo';

    const modalRef = this.modal.create({
      nzTitle,
      nzClassName: 'uploadHeader',
      nzWidth: '800px',
      nzFooter: null,
      nzContent: UploadHeaderComponent,
      nzComponentParams: {
        headerImg: this.organizationInfo.logo
      },

      nzOnOk: (selectorComponent) => {
        console.log(selectorComponent.croppedImage);

        this.organizationInfo.logo = selectorComponent.croppedImage
        this.saveOrgInfo();
        this.msg.success('保存成功')
      },
      nzOnCancel: (selectorComponent) => {
      }
    });

  }
  openBgConfigModal() {
    const nzTitle = '上传封面背景';

    const modalRef = this.modal.create({
      nzTitle,
      nzClassName: 'uploadHeader',
      nzWidth: '1000px',
      nzFooter: null,
      nzContent: UploadBackgroundComponent,
      nzComponentParams: {
        headerImg: this.organizationInfo.coverUrl
      },

      nzOnOk: (selectorComponent) => {
        console.log(selectorComponent.croppedImage);

        this.organizationInfo.coverUrl = selectorComponent.croppedImage
        this.saveOrgInfo();
        this.msg.success('保存成功')
      },
      nzOnCancel: (selectorComponent) => {
      }
    });
  }
}
